<?php


namespace app\common\model\mysql\system;


use app\common\exception\MessageException;
use app\common\model\mysql\BaseModel;
use think\model\concern\SoftDelete;

class Role extends BaseModel
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    // 设置当前模型对应的完整数据表名称
    protected $table = 'sys_role';

    // 定义主键 alter table users AUTO_INCREMENT=10000;
    protected $pk = 'id';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 模型初始化
    protected static function init()
    {
        // TODO:初始化内容
    }

    // 检查分类名是否存在
    public static function checkName($name, $id = null)
    {
        if (!$name) {
            throw new MessageException(['msg' => '角色名称不合法']);
        }

        if (isset($id)) {
            return self::where('name', $name)->where('id', '<>', $id)->find();
        }

        return self::where('name', $name)->find();
    }

    // 列表查询
    public static function list($params) {
        // 分页查询
        $order = [
            'sort' => 'acs',
            'update_time' => 'desc',
            'create_time' => 'desc',
            'id' => 'desc'
        ];

        $currentPage = $params['current'] ?? 1;
        $pageSize = $params['pageSize'] ?? 30;

        $where = [];
        // 筛选
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        if (isset($params['status']) && $params['status'] != '') {
            $where[] = ['status', '=', $params['status']];
        }

        $query = self::where($where)->order($order);

        // 查询
        $count = $query->count();
        $list = $query->page($currentPage, $pageSize)->select();

        return [
            'total' => $count,
            'totalPage' => ceil($count / $pageSize),
            'current' => $currentPage,
            'pageSize' => $pageSize,
            'list' => $list,
        ];
    }

    // 添加
    public static function add(array $params)
    {
        return self::create([
            'name' => $params['name'],
            'sort' => $params['sort'] ?? 0,
            'status' => $params['status'],
            'remark' => $params['remark'] ?? '',
        ]);
    }

    public static function edit(array $params)
    {
        try {
            return self::update([
                'id' => $params['id'],
                'name' => $params['name'],
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'],
                'remark' => $params['remark'] ?? '',
            ]);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public static function remove(array $params)
    {
        try {
            self::destroy($params['id']);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}